<template>
  <div>
    <div class="comp-tree">
      <el-button class="comp-tr-top" type="primary" v-if="type" size="small" @click="handleAddTop" style="width: 100%">
        {{ btnTitle }}
      </el-button>
      <!-- tree -->
      <el-input placeholder="输入关键字进行过滤~" v-model="filterText"></el-input>
      <el-tree ref="SlotTree" :data="treeList" :props="defaultProps" :current-node-key="currentNodekey"
        :filter-node-method="filterNode" :highlight-current="true" :expand-on-click-node="false" :node-key="NODE_KEY"
        :default-expanded-keys="showKey" @node-click="handleNodeClick">
        <div class="comp-tr-node" slot-scope="{ node, data }" style="width: 5rem">
          <i v-if="data.parentId === '0'" class="el-icon-folder"></i>
          <i v-else class="el-icon-collection-tag"></i>
          <span style="margin-left: 10px"></span>
          <!-- 编辑状态 -->
          <template v-if="node.isEdit">
            <el-input v-model="data.name" autofocus size="mini" :ref="'slotTreeInput' + data[NODE_KEY]"
              @blur.stop="handleInput(node, data)" @keyup.enter.native="handleInput(node, data)"></el-input>
          </template>

          <!-- 非编辑状态 -->
          <template v-else>
            <!-- 名称： 新增节点增加class（is-new） -->
            <span :class="[data[NODE_KEY] < NODE_ID_START ? 'is-new' : '', 'comp-tr-node--name']">
              {{ node.label }}
            </span>
            <el-dropdown placement="top" style="margin-left: 10%">
              <span class="el-dropdown-link">
                <i class="el-icon-more el-icon--right"></i>
              </span>
              <el-dropdown-menu>
                <!-- 新增 -->
                <el-tooltip class="item" effect="dark" content="添加子节点" placement="top">
                  <el-button icon="el-icon-plus" size="large" circle title="添加子节点" @click="handleAdd(node, data)"
                    style="border: none; background-color: transparent; transform: scale(1.1)"></el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="查看详情" placement="top">
                  <!-- 查看 -->
                  <el-button icon="el-icon-document" size="large" circle title="查看节点详情" @click="handleLook(node, data)"
                    style="border: none; background-color: transparent; transform: scale(1.1)"></el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="编辑节点" placement="top">
                  <el-button icon="el-icon-edit" size="large" circle title="编辑节点" @click="handleEdit(node, data)"
                    style="border: none; background-color: transparent; transform: scale(1.1)"></el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="删除节点" placement="top">
                  <el-button icon="el-icon-delete" size="large" circle title="删除节点"
                    @click="handleDeletetree(node, data)"
                    style="border: none; background-color: transparent; transform: scale(1.1)"></el-button>
                </el-tooltip>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </div>
      </el-tree>
      <treeData ref="treeForm" @getTreeList="getTreeList" />
    </div>
  </div>
</template>

<script>
import treeData from './treeData.vue'
import { fetchMasterdataDirectoryList, deleteMasterdataDirectory } from '@/api/masterdata/masterdataDirectory'

export default {
  name: 'DatagovernanceFrontendIndex',
  props: {
    ancestralId: {
      type: [String, Number],
      default: '0',
      required: true,
    },
    btnTitle: {
      type: [String],
      default: '创建目录',
      required: true,
    },
    type: {
      type: [Boolean],
      default: false,
      required: true,
    },
    //选择项的类型
    expandType: {
      type: [String, Number],
      required: true,
    },
  },
  components: { treeData },
  data() {
    return {
      filterText: '',
      tableKey: 0,
      treeList: [],
      list: null,
      total: 0,
      multipleSelection: [],
      listLoading: true,
      pageArray: this.$store.getters.pageArray,
      listQuery: {
        ancestralId: this.ancestralId + '',
      },
      NODE_KEY: 'id', // id对应字段
      MAX_LEVEL: 5, // 设定最大层级
      NODE_ID_START: 0, // 新增节点id，逐次递减
      startId: null,
      defaultProps: {
        // 默认设置
        children: 'children',
        label: 'name',
      },
      initParam: {
        // 新增参数
        name: '新增节点',
        parentId: 0,
        children: [],
      },
      showKey: [],
      directoryId: '', //选中目录ID
      currentNodekey: '',
    }
  },
  watch: {
    filterText(val) {
      this.$refs.SlotTree.filter(val)
    },
  },
  mounted() {
    this.getTreeList()
  },

  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleAddTop() {
      // 添加顶部节点
      let obj = JSON.parse(JSON.stringify(this.initParam)) // copy参数
      obj.parentId = 0
      obj.name = ''
      obj[this.NODE_KEY] = --this.startId // 节点id：逐次递减id
      // console.log(obj,'顶部参数')
      this.$refs.treeForm.handleCreate(obj, this.ancestralId)
    },
    handleNodeClick(data) {
      this.listQuery = data
      this.$emit('getId', this.listQuery)
    },
    handleAdd(_node, _data) {
      // 新增节点
      console.log(_node, _data)
      // // 判断层级
      if (_node.level >= this.MAX_LEVEL) {
        this.$message.warning('当前已达到' + this.MAX_LEVEL + '级，无法新增！')
        return false
      }
      // 参数修改
      let obj = JSON.parse(JSON.stringify(this.initParam)) // copy参数
      obj.parentId = _data.id // 父id
      obj.name = ''
      obj[this.NODE_KEY] = --this.startId // 节点id：逐次递减id
      this.$refs.treeForm.handleCreate(obj, this.ancestralId)
    },
    handleDeletetree(_node, _data) {
      // 删除节点

      console.log(_node, _data)
      // 判断是否存在子节点
      if (_data.children && _data.children.length !== 0) {
        this.$message.error('此节点有子级，不可删除！')
        return false
      } else {
        // 删除操作
        let DeletOprate = () => {
          this.$nextTick(() => {
            if (this.$refs.SlotTree) {
              deleteMasterdataDirectory(_data.id).then((res) => {
                console.log(res)
                this.$message.success('删除成功！')
                this.$refs.SlotTree.remove(_data)
              })
            }
          })
        }

        // 二次确认
        let ConfirmFun = () => {
          this.$confirm('是否删除此节点？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              DeletOprate()
            })
            .catch(() => { })
        }

        // 判断是否新增： 新增节点直接删除，已存在的节点要二次确认
        _data[this.NODE_KEY] < this.NODE_ID_START ? DeletOprate() : ConfirmFun()
      }
    },
    handleEdit(_node, _data) {
      // 编辑节点
      console.log(_node, _data)
      let obj = {
        id: _data.id,
        parentId: _data.parentId,
        name: _data.name,
        description: _data.description,
      }
      this.$refs.treeForm.handleUpdate(obj, this.ancestralId)
    },
    handleLook(_node, _data) {
      let obj = {
        id: _data.id,
        parentId: _data.parentId,
        name: _data.name,
        description: _data.description,
      }
      this.$refs.treeForm.handleLook(obj)
    },
    // getTreeCchuli(item) {
    //   let arr = []
    //   item.map((v, i) => {
    //     if (v.children && v.children.length) {
    //       this.getTreeCchuli(v.children)
    //     } else {
    //       if (v.isDirectory == 'null') {

    //       }
    //     }
    //     return arr
    //   })
    // },
    getTreeList() {
      console.log(this.ancestralId,'1111111111111');
      this.listQuery = {
        page: 1,
        limit: 25,
        ancestralId: this.ancestralId,
      }
      this.listLoading = true

      fetchMasterdataDirectoryList(this.listQuery).then((response) => {
        if (response.data.code === 200) {
          // this.treeList = this.getTreeCchuli(response.data.data)
          this.treeList = response.data.data
          // console.log(this.treeList);
          if (this.treeList.length > 0) {
            this.$emit('getTree', this.treeList)
            if (this.expandType == '1') {
              this.currentNodekey = this.treeList[0].id
              this.handleNodeClick(this.treeList[0])
              this.$emit('getList', this.treeList[0])
            } else if (this.expandType == '2') {
              this.currentNodekey = this.getFirstNode(this.treeList)[0].id
              this.handleNodeClick(this.getFirstNode(this.treeList)[0])
              this.$emit('getList', this.getFirstNode(this.treeList)[0])
            }

            // this.getList()
            //获取列表详情
            this.$nextTick(() => {
              this.$refs.SlotTree.setCurrentKey(this.currentNodekey) //一定要加这个选中了否则样式没有出来
            })
          }
          this.treeList.forEach((item) => {
            this.showKey.push(item.id)
          })
          this.listLoading = false
          // this.$refs.form.setList(this.treeList)
        } else {
          this.$message.error(response.data.msg)
        }
        this.listLoading = false
      })
    },

    getFirstNode(treeList) {
      if (!Array.isArray(treeList) || treeList.length === 0) {
        // 确保 treeList 是一个非空数组
        return null
      }

      if (treeList[0].isDirectory === '1') {
        // 如果第一个节点是文件夹（目录）
        return treeList
      } else {
        // 否则递归查找子树
        return this.getFirstNode(treeList[0].children)
      }
    },
  },
}
</script>

<style scoped>
.el-tree {
  width: 100% !important;
  min-width: auto !important;
}

.el-tree-node__content {
  height: 32px !important;
}

.el-tree-node .is-current .is-focusable {
  background: rebeccapurple !important;
}
</style>
